<template>
  <div class="home">
    <!-- 页面标题和统计卡片 -->
    <div class="header-section">
      <div class="welcome-text">
        <h1>文章搜索系统</h1>
        <p class="subtitle">快速检索、分类管理、数据统计</p>
      </div>
      <div class="quick-stats">
        <el-row :gutter="20">
          <el-col :span="6" v-for="item in statisticsCards" :key="item.title">
            <div class="stat-card" :class="`stat-card--${item.type}`">
              <div class="stat-card__icon">
                <el-icon :size="24">
                  <component :is="item.icon" />
                </el-icon>
              </div>
              <div class="stat-card__content">
                <div class="stat-card__value">{{ item.value }}</div>
                <div class="stat-card__title">{{ item.title }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    
    <!-- 主要内容区 -->
    <div class="main-content">
      <div class="content-header">
        <h2>文章列表</h2>
        <el-button type="primary" @click="showEditDialog">
          <el-icon><Plus /></el-icon>新增文章
        </el-button>
      </div>
      <div class="article-container">
        <ArticleList ref="articleListRef" />
      </div>
    </div>

    <!-- 文章编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑文章' : '新建文章'"
      width="80%"
      :fullscreen="false"
      :close-on-click-modal="false"
      @close="resetForm"
    >
      <el-form :model="form" label-width="80px" class="article-form">
        <el-form-item label="标题" required>
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" required>
          <div class="markdown-editor">
            <MdEditor
              v-model="form.content"
              :height="400"
              :toolbars="toolbars"
            />
          </div>
        </el-form-item>
        <el-form-item label="分类">
          <el-select
            v-model="form.category"
            placeholder="请选择分类"
            clearable
            filterable
            allow-create
            style="width: 100%"
          >
            <el-option
              v-for="category in store.categories"
              :key="category"
              :label="category"
              :value="category"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select
            v-model="form.tags"
            placeholder="请选择标签"
            multiple
            clearable
            filterable
            allow-create
            collapse-tags
            style="width: 100%"
          >
            <el-option
              v-for="tag in store.tags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Document, Collection, Tickets, Star, Plus } from '@element-plus/icons-vue'
import ArticleList from '@/components/ArticleList.vue'
import { getStatistics, createArticleApi, updateArticleApi } from '@/api/article'
import { handleError } from '@/utils/error-handler'
import type { ArticleStatistics } from '@/api/types'
import { useArticleStore } from '@/stores/article'
import { ElMessage } from 'element-plus'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'

const store = useArticleStore()
const articleListRef = ref()

const statistics = ref<ArticleStatistics>({
  totalArticles: 0,
  totalCategories: 0,
  totalTags: 0,
  mostUsedCategory: ''
})

// 统计卡片数据
const statisticsCards = computed(() => [
  {
    title: '文章总数',
    value: statistics.value.totalArticles,
    icon: Document,
    type: 'primary'
  },
  {
    title: '分类总数',
    value: statistics.value.totalCategories,
    icon: Collection,
    type: 'success'
  },
  {
    title: '标签总数',
    value: statistics.value.totalTags,
    icon: Tickets,
    type: 'warning'
  },
  {
    title: '最常用分类',
    value: statistics.value.mostUsedCategory || '-',
    icon: Star,
    type: 'danger'
  }
])

async function loadStatistics() {
  try {
    const response = await getStatistics()
    if (response?.data?.data) {
      statistics.value = response.data.data
    }
  } catch (error) {
    handleError(error)
  }
}

// 编辑对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)

const form = ref({
  id: '',
  title: '',
  content: '',
  category: '',
  tags: [] as string[]
})

function showEditDialog() {
  isEdit.value = false
  dialogVisible.value = true
}

function resetForm() {
  form.value = {
    id: '',
    title: '',
    content: '',
    category: '',
    tags: []
  }
}

async function handleSave() {
  if (!form.value.title || !form.value.content) {
    ElMessage.warning('请填写标题和内容')
    return
  }

  saving.value = true
  try {
    const data = {
      ...form.value,
      tags: form.value.tags.join(',')
    }

    if (isEdit.value) {
      await updateArticleApi(data)
      ElMessage.success('更新成功')
    } else {
      await createArticleApi(data)
      ElMessage.success('创建成功')
    }

    dialogVisible.value = false
    // 刷新文章列表
    articleListRef.value?.fetchData()
  } catch (error) {
    handleError(error)
  } finally {
    saving.value = false
  }
}

// 配置编辑器工具栏
const toolbars = [
  'bold',
  'underline',
  'italic',
  'strikethrough',
  '-',
  'title',
  'sub',
  'sup',
  'quote',
  'unorderedList',
  'orderedList',
  '-',
  'codeRow',
  'code',
  'link',
  'image',
  'table',
  '-',
  'preview',
  'fullscreen',
  '-',
  'save'
]

onMounted(() => {
  loadStatistics()
  // 加载分类��标签数据
  store.fetchCategories()
  store.fetchTags()
})
</script>

<style scoped lang="scss">
.home {
  min-height: 100vh;
  background-color: #f5f7fa;

  .header-section {
    background: linear-gradient(135deg, #409eff 0%, #36d1dc 100%);
    padding: 40px 24px;
    color: white;
    margin-bottom: 24px;
    position: relative;
    overflow: hidden;

    // 添加背景装饰
    &::before {
      content: '';
      position: absolute;
      top: -50%;
      left: -50%;
      width: 200%;
      height: 200%;
      background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 60%);
      animation: rotate 30s linear infinite;
    }

    .welcome-text {
      text-align: center;
      margin-bottom: 32px;
      position: relative;

      h1 {
        font-size: 32px;
        font-weight: 600;
        margin: 0 0 12px;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }

      .subtitle {
        font-size: 16px;
        opacity: 0.9;
        margin: 0;
      }
    }

    .quick-stats {
      max-width: 1600px;
      margin: 0 auto;
      position: relative;
      padding: 0 24px;
    }
  }

  .stat-card {
    background: rgba(255, 255, 255, 0.15);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    padding: 20px;
    display: flex;
    align-items: center;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

    &:hover {
      transform: translateY(-5px);
      background: rgba(255, 255, 255, 0.2);
      border-color: rgba(255, 255, 255, 0.3);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    }

    &__icon {
      width: 48px;
      height: 48px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      background: rgba(255, 255, 255, 0.2);
      transition: all 0.3s;
    }

    &__content {
      flex: 1;
    }

    &__value {
      font-size: 24px;
      font-weight: 600;
      margin-bottom: 4px;
    }

    &__title {
      font-size: 14px;
      opacity: 0.9;
    }
  }

  .main-content {
    max-width: 1600px;
    margin: -60px auto 0;
    padding: 0 24px;
    position: relative;
    z-index: 1;

    .content-header {
      background: white;
      border-radius: 12px;
      padding: 24px 36px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
      transition: all 0.3s;

      &:hover {
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
      }

      h2 {
        font-size: 20px;
        font-weight: 600;
        color: #303133;
        margin: 0;
      }
    }

    .article-container {
      background: white;
      border-radius: 12px;
      padding: 24px 36px;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
      transition: all 0.3s;

      &:hover {
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
      }
    }
  }
}

// 添加动画
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 响应式布局
@media screen and (max-width: 1680px) {
  .home {
    .main-content,
    .header-section .quick-stats {
      max-width: 1400px;
    }
  }
}

@media screen and (max-width: 1440px) {
  .home {
    .main-content,
    .header-section .quick-stats {
      max-width: 1200px;
    }
  }
}

@media screen and (max-width: 1200px) {
  .home {
    .main-content,
    .header-section .quick-stats {
      max-width: 100%;
      padding: 0 20px;
    }
  }
}

@media screen and (max-width: 768px) {
  .home {
    .header-section {
      padding: 30px 16px;

      .welcome-text {
        h1 {
          font-size: 24px;
        }
      }
    }

    .quick-stats {
      .el-col {
        width: 100% !important;
      }
    }

    .main-content {
      padding: 0 16px;
    }
  }
}

.article-form {
  :deep(.el-form-item__content) {
    width: calc(100% - 80px); // 减去 label 的宽度
  }
}

.markdown-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  width: 100%;
  
  :deep(.md-editor) {
    border: none;
    width: 100%;
  }

  :deep(.md-editor-toolbar) {
    width: 100%;
  }

  :deep(.md-editor-content) {
    width: 100%;
  }
}

:deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: 90vh;
  max-width: 90vw;
  
  .el-dialog__body {
    flex: 1;
    overflow: auto;
    padding: 20px;
  }

  .el-form-item {
    margin-bottom: 22px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
}
</style> 